from math import sqrt
import probabilityDistributions

'''
Created on 25.5.2011

@author: Martin Vegi Kysel
@about Quick stats functions written by Tecumseh Fitch -- should be checked (esp. confidenceInterval)
'''


def even(x):
    if x % 2 == 0:
        return True
    else:
        return False
    
def total(data):
    N = len(data)
    if N == 0:
        print "Error: Statistics: Total: data list is empty!"
    total = sum(data)
    return total

def mean(data):
    N = len(data)

    return total(data)/(N)



def stdDev(data):
    ''' Caluculate standard deviation of a sample (sumSquares/(N-1)'''
    dataMean = mean(data)
    sumSquared = sum([(i-dataMean)**2 for i in data])
    
    length = len(data)-1 or 1 # we could have a long argument about whether N or N-1 should be used (sample versus population mean)
    stdDeviation = sqrt(sumSquared/length)
    return stdDeviation

def median(data):
    # quick and dirty, just cuts sorted data in half! Should calculate in between value too!!
    s = list(data) # make a copy
    s.sort()
    N = len(data)
    splitIndex = N/int(2) # note integer divide guarantees integer index, will work in Python 3
    if even(N):
        low = s[splitIndex]
        high = s[splitIndex - 1]#needs to be minus one, not plus one. GWF
        median = (low + high)/2.0#brackets.GWF
    else:
        median = s[splitIndex]
    return median

def confidenceInterval(data, intervalWidth = 0.05):
    standard_deviation = stdDev(data)
    s_m = standard_deviation/sqrt(len(data))
    confidence = probabilityDistributions.tinv(intervalWidth, len(data)-1) * s_m
    return confidence
